
package model;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;

import utils.Command;
import utils.MyConnection;

public class P2PThreadModel extends Thread {
    
    private final Socket socket;
    private ObjectInputStream in;
    private ObjectOutputStream out;
    
    public P2PThreadModel(Socket socket) {
        this.socket = socket;
        start();
    }
    
    public void run() {
        
        String[] received;
        
        try {
            in = new ObjectInputStream(socket.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        
        received = MyConnection.receive(in);
        
        switch (received[MyConnection.COMMAND]) {
            case Command.READ_FILE:
                try {
                    optionReadFile(received[MyConnection.MESSAGE]);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                break;
            case Command.UPDATE_FILE:
                try {
                    optionUpdateFile(received[MyConnection.MESSAGE]);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
        
    }
    
    private void optionReadFile(String fileName) throws IOException {
        File file = new File(fileName);
        InputStream inAux = new FileInputStream(file);
        OutputStream outAux = socket.getOutputStream();
        MyConnection.copy(inAux, outAux);
        inAux.close();
        outAux.close();
    }
    
    private void optionUpdateFile(String fileName) throws IOException {
        File file = new File(fileName);
        file.delete();
        InputStream inAux = socket.getInputStream();
        OutputStream outAux = new FileOutputStream(fileName);
        
        MyConnection.copy(inAux, outAux);
        inAux.close();
        outAux.close();
    }
    
}
